﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using RearLivestock.Common.Domains.hq;
using RearLivestock.Common.Domains.wbx;
using RearLivestock.Common.Dtos;
using RearLivestock.Common.Infrastructure.Interface;
using RearLivestock.RBAC.ErrorCodeEnum;
using System.Reflection;

namespace RearLivestock.Beginning.Api.Application.Command.PigletsWeanings
{
    /// <summary>
    /// 仔猪断奶显示Handler
    /// </summary>
    public class SearchPigletsWeaningHandler : IRequestHandler<SearchPigletsWeaningCommand, Result<PageResultDto<PigletsWeaningDto>>>
    {
        private readonly IMapper mapper;
        /// <summary>
        /// 仔猪断奶
        /// </summary>
        private readonly IBaseRepository<PigletsWeaning> pigletsWeaningrepository;
        /// <summary>
        /// 栏位
        /// </summary>
        private readonly IBaseRepository<Fields> fieldsrepository;
        /// <summary>
        /// 栋舍
        /// </summary>
        private readonly IBaseRepository<Bedrooms> bedroomsrepository;
        /// <summary>
        /// 猪只基本信息
        /// </summary>
        private readonly IBaseRepository<BasicInformation> basicInformationrepository;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<SearchPigletsWeaningHandler> _logger;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="pigletsWeaningrepository"></param>
        /// <param name="logger"></param>
        /// <param name="fieldsrepository"></param>
        /// <param name="bedroomsrepository"></param>
        /// <param name="basicInformationrepository"></param>
        public SearchPigletsWeaningHandler(IMapper mapper, IBaseRepository<PigletsWeaning> pigletsWeaningrepository, ILogger<SearchPigletsWeaningHandler> logger, IBaseRepository<Fields> fieldsrepository, IBaseRepository<Bedrooms> bedroomsrepository, IBaseRepository<BasicInformation> basicInformationrepository)
        {
            this.mapper = mapper;
            this.pigletsWeaningrepository = pigletsWeaningrepository;
            _logger = logger;
            this.fieldsrepository = fieldsrepository;
            this.bedroomsrepository = bedroomsrepository;
            this.basicInformationrepository = basicInformationrepository;
        }
        /// <summary>
        /// 仔猪断奶显示
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result<PageResultDto<PigletsWeaningDto>>> Handle(SearchPigletsWeaningCommand request, CancellationToken cancellationToken)
        {
            var result = new Result<PageResultDto<PigletsWeaningDto>>() { Code = (int)CommonErrorCode.Search };
            var page = new PageResultDto<PigletsWeaningDto>() { TotalCount = 0, PageCount = 0, List = new List<PigletsWeaningDto>() };
            try
            {
                var pigletsWeaning = await (from a in await pigletsWeaningrepository.GetAll()
                                            join b in await basicInformationrepository.GetAll()
                                            on a.BasicInforId equals b.BasicInforId
                                            join c in await fieldsrepository.GetAll()
                                            on a.Transferfield equals c.FieldId
                                            join d in await bedroomsrepository.GetAll()
                                            on a.Transferbuilding equals d.BedroomId
                                            select new PigletsWeaningDto()
                                            {
                                                PigletsWeaningId = a.PigletsWeaningId,
                                                EarNumber = b.EarNumber,
                                                MotherEarNumber = b.MotherEarNumber,
                                                Gender = a.Gender,
                                                Currentbuilding = a.Currentbuilding,
                                                BedroomName = d.BedroomName,
                                                Currentfield = a.Currentfield,
                                                FieldName = c.FieldName,
                                                Transferbuilding = a.Transferbuilding,
                                                Transferfield = a.Transferfield,
                                                WeaningDate = a.WeaningDate,
                                                WeaningWeight = a.WeaningWeight,
                                                DocumentNo = a.DocumentNo,
                                                SerialNo = a.SerialNo
                                            }).ToListAsync();
                //断奶日期开始时间
                if (request.SDate != null)
                {
                    pigletsWeaning = pigletsWeaning.Where(x => x.WeaningDate >= request.SDate).ToList();
                }
                //断奶日期结束时间
                if (request.ODate != null)
                {
                    pigletsWeaning = pigletsWeaning.Where(x => x.WeaningDate <= request.ODate).ToList();
                }
                page.TotalCount = pigletsWeaning.Count();
                page.PageCount = (int)Math.Ceiling(page.TotalCount * 1.0 / request.PageSize);
                page.List = pigletsWeaning.OrderBy(x => x.PigletsWeaningId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
                result.Data = page;
                result.Msg = "仔猪断奶显示成功";
            }
            catch (Exception ex)
            {
                _logger.LogError("仔猪断奶显示失败" + ex.Message);
                throw;
            }
            return result;
        }
    }
}
